package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    private static final String KEY_PREFIX = "user:verify:code:phone";

    @Override
    public Boolean existsData(String data, Integer type) {
//        代码健壮性判断,

        if(type != 1&& type != 2){
            throw new LyException(400, "请求参数有误");
        }

        Integer count = query().eq("username", data)
                .eq("phone", data)
                .count();
//        count大于0说明用户存在
        return count > 0;
    }
    /*
    * 用户验证码发送
    * */
    @Override
    public void sendCode(String phone) {

//        对手机号进行验证
        if(!RegexUtils.isPhone(phone)){
//            手机号格式不正确
            throw new LyException(400, "手机号格式不正确");
        }

//        生成验证码,长度固定为6位
        String code = RandomStringUtils.randomNumeric(6);
//        验证码保存到redis 过期时间为5分钟
        redisTemplate.opsForValue().set(KEY_PREFIX + phone,code,5, TimeUnit.MINUTES);
//        发送MQ消息,通知SMS服务，发送短信验证码到指定手机号
        HashMap<String, String> msg = new HashMap<>();
        msg.put("phone", phone);
        msg.put("code", code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);
    }
        /*
        * 用户注册
        * */
    @Transactional
    @Override
    public void register(User user, String code) {
//        校验验证码
//        取出redis中的验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
//        比较验证码
        if(!StringUtils.equals(code,cacheCode)){
            throw new LyException(400, "验证码错误");
        }

//        对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
//        写入数据库
        save(user);

    }
        /*
        * 根据手机号、密码查询用户信息
        * */
    @Override
    public UserDTO queryUserByPhoneAndPasssword(String username, String password) {
//        根据用户名查询
        User user = query().eq("username", username).one();
//        判断用户是否存在
        if(user ==  null){
            throw new LyException(400, "用户名或密码错误");
        }
//          校验密码
        if(!passwordEncoder.matches(password,user.getPassword())){
            throw new LyException(400, "用户名或密码错误");
        }

//        返回用户信息
        return new UserDTO(user);
    }

}